<?php namespace App\Api\Http\Middleware;

use Closure;

class ApiAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->exceptToken($request)) {
            return $next($request);
        }

        if (access()->check()) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return response('Unauthenticated.', 401);
    }

    /**
     * @param  \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function exceptToken($request)
    {
        $route_name = $request->route()->getName();

        return in_array($route_name, ['api.login']);
    }
}
